<template>
    <div class="edit-page">
        <!-- 店铺封面图 -->
        <div class="store-header">
            <div class="cover-image-container">
                <img v-if="storeInfo.url" :src="storeInfo.url" class="cover-image" alt="店铺封面" />
                <div class="upload-placeholder" @click="triggerUpload">
                    <el-icon>
                        <Edit />
                    </el-icon>
                    <span>点击修改封面图</span>
                </div>
            </div>
        </div>

        <!-- 店铺信息列表 -->
        <div class="store-info-container">
            <div class="info-item">
                <div class="label">店铺名称</div>
                <div class="value">
                    {{ storeInfo.name }}
                    <el-button link type="warning" size="small" @click="editField('name')">
                        <el-icon>
                            <Edit />
                        </el-icon> 修改
                    </el-button>
                </div>
            </div>

            <div class="info-item">
                <div class="label">店铺描述</div>
                <div class="value">
                    <div class="description-text">{{ storeInfo.description || '暂无描述' }}</div>
                    <el-button link type="warning" size="small" @click="editField('description')">
                        <el-icon>
                            <Edit />
                        </el-icon> 修改
                    </el-button>
                </div>
            </div>

            <div class="info-item">
                <div class="label">店铺地址</div>
                <div class="value">
                    {{ storeInfo.address }}
                    <el-button link type="warning" size="small" @click="editField('address')">
                        <el-icon>
                            <Edit />
                        </el-icon> 修改
                    </el-button>
                </div>
            </div>

            <div class="info-item">
                <div class="label">联系电话</div>
                <div class="value">
                    {{ storeInfo.phone }}
                    <el-button link type="warning" size="small" @click="editField('phone')">
                        <el-icon>
                            <Edit />
                        </el-icon> 修改
                    </el-button>
                </div>
            </div>

            <div class="info-item">
                <div class="label">营业时间</div>
                <div class="value">
                    <div class="time-range">
                        {{ storeInfo.openTime }} - {{ storeInfo.closeTime }}
                    </div>
                    <div class="edit-buttons">
                        <el-button link type="warning" size="small" @click="editField('openTime')">
                            <el-icon>
                                <Edit />
                            </el-icon> 开始时间
                        </el-button>
                        <el-button link type="warning" size="small" @click="editField('closeTime')">
                            <el-icon>
                                <Edit />
                            </el-icon> 结束时间
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 隐藏的文件输入组件 -->
        <input type="file" ref="fileInputRef" class="hidden-file-input" @change="handleFileChange" accept="image/*" />

        <!-- 编辑对话框 -->
        <el-dialog v-model="editDialog.visible" :title="editDialog.title" class="adaptive-dialog"
            :before-close="handleClose" width="400px">
            <template v-if="editDialog.field === 'name'">
                <el-input v-model="tempValue" placeholder="请输入店铺名称" />
            </template>

            <template v-else-if="editDialog.field === 'description'">
                <el-input v-model="tempValue" type="textarea" :rows="3" placeholder="请输入店铺描述" autosize />
            </template>

            <template v-else-if="editDialog.field === 'address'">
                <el-input v-model="tempValue" placeholder="请输入详细地址" />
            </template>

            <template v-else-if="editDialog.field === 'phone'">
                <el-input v-model="tempValue" placeholder="请输入联系电话" maxlength="11" show-word-limit
                    :disabled="!editDialog.visible" />
            </template>

            <template v-else-if="editDialog.field === 'openTime' || editDialog.field === 'closeTime'">
                <el-time-picker v-model="tempValue" placeholder="选择时间" format="HH:mm" value-format="HH:mm" clearable
                    style="width: 100%;" />
            </template>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialog.visible = false" class="btn cancelBtn">取消</el-button>
                    <el-button type="primary" @click="saveField(editDialog.field)" color="#ffc200"
                        class="btn">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { upload } from '@/services/api/common'
import { Edit } from '@element-plus/icons-vue'
import { useStoreInfoStore } from '@/store'
import type { StoreBaseInfo } from '@/types/store'
import { updateStoreInfo } from '@/services/api/store'

// ==================== Pinia Store ====================
const storeInfoStore = useStoreInfoStore()

// 计算属性，从 Pinia 中获取店铺信息
const storeInfo = computed<StoreBaseInfo>(() => storeInfoStore.getStoreInfo || {
    name: '',
    description: '',
    url: '',
    address: '',
    phone: '',
    openTime: '',
    closeTime: '',
    storeId: null
})

// ==================== 数据定义 ====================
// 编辑对话框状态
const editDialog = reactive({
    visible: false,
    field: '',
    title: ''
})

// 文件输入引用
const fileInputRef = ref()

// 临时值，用于编辑时存储
const tempValue = ref('')

// ==================== 文件上传相关 ====================
// 触发文件上传
const triggerUpload = () => {
    if (fileInputRef.value) {
        fileInputRef.value.click()
    }
}

// 处理文件变更
const handleFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]

    if (file) {
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            ElMessage.error('只能上传图片文件!')
            resetFileInput(target)
            return
        }

        // 检查文件大小
        if (file.size > 2 * 1024 * 1024) {
            ElMessage.error('图片大小不能超过 2MB!')
            resetFileInput(target)
            return
        }

        try {
            const res = await upload(file)
            // 更新 Pinia 中的数据
            storeInfoStore.updateStoreInfoField('url', res.data)
            // 调用 API 更新服务器数据
            await updateStoreInfo({ ...storeInfo.value, url: res.data })
            ElMessage.success('图片上传成功')
        } catch (error) {
            ElMessage.error('图片上传失败')
        } finally {
            resetFileInput(target)
        }
    }
}

// 重置文件输入框
const resetFileInput = (target: HTMLInputElement) => {
    target.value = ''
}

// ==================== 字段编辑相关 ====================
// 编辑字段
const editField = (field: string) => {
    editDialog.field = field
    editDialog.title = getFieldTitle(field)
    tempValue.value = storeInfo.value[field as keyof StoreBaseInfo] as string
    editDialog.visible = true
}

// 获取字段标题
const getFieldTitle = (field: string): string => {
    const titles: Record<string, string> = {
        'name': '修改店铺名称',
        'description': '修改店铺描述',
        'address': '修改店铺地址',
        'phone': '修改联系电话',
        'openTime': '修改营业开始时间',
        'closeTime': '修改营业结束时间'
    }
    return titles[field] || '修改信息'
}

// 保存字段修改
const saveField = async (field: string) => {
    // 添加基本验证
    if (field === 'phone' && tempValue.value && !/^1[3-9]\d{9}$/.test(tempValue.value)) {
        ElMessage.error('请输入正确的手机号')
        return
    }

    try {
        // 更新 Pinia 中的数据
        storeInfoStore.updateStoreInfoField(field as keyof StoreBaseInfo, tempValue.value as never)

        // 调用 API 更新服务器数据
        await updateStoreInfo(storeInfo.value)

        editDialog.visible = false
    } catch (error) {
        ElMessage.error('保存失败')
        // 如果保存失败，回滚 Pinia 中的数据
        storeInfoStore.setStoreInfo(storeInfo.value)
    }
}

// ==================== 对话框相关 ====================
// 关闭对话框时的处理
const handleClose = () => {
    editDialog.visible = false
}
</script>

<style scoped>
.edit-page {
    padding: 20px;
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    max-width: 800px;
    margin: 0 auto;
}

.store-header {
    text-align: center;
    margin-bottom: 30px;
}

.cover-image-container {
    position: relative;
    width: 100%;
    max-width: 400px;
    margin: 0 auto;
    overflow: hidden;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.cover-image {
    width: 100%;
    height: 300px;
    display: block;
    transition: transform 0.3s ease;
    object-fit: cover;
}

.cover-image:hover {
    transform: scale(1.02);
}

.upload-placeholder {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.cover-image-container:hover .upload-placeholder {
    opacity: 1;
}

.upload-placeholder .el-icon {
    font-size: 24px;
    margin-bottom: 8px;
}

.upload-placeholder span {
    font-size: 14px;
    font-weight: 500;
}

.store-info-container {
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.info-item {
    padding: 16px 0;
    border-bottom: 1px solid #ebeef5;

    &:last-child {
        border-bottom: none;
    }
}

.label {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
    font-weight: 500;
}

.value {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 0;
}

.description-text {
    font-size: 14px;
    line-height: 1.6;
    color: #333;
    word-break: break-word;
}

.edit-buttons {
    display: flex;
    gap: 8px;
    margin-top: 8px;
}

.time-range {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

.dialog-footer {
    text-align: right;
}

/* 隐藏的文件输入组件 */
.hidden-file-input {
    display: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .edit-page {
        padding: 15px;
    }

    .cover-image-container {
        max-width: 100%;
    }

    .info-item {
        padding: 12px 0;
    }

    .label {
        font-size: 13px;
    }

    .value {
        flex-direction: column;
        align-items: flex-start;
    }

    .edit-buttons {
        flex-direction: column;
        gap: 4px;
    }

    .adaptive-dialog {
        --el-dialog-width: 95%;
        --el-dialog-margin-top: 10vh;
    }

    .adaptive-dialog .el-dialog__body {
        padding: 15px;
        max-height: 50vh;
    }

    .adaptive-dialog .el-dialog__header {
        padding: 15px 15px 10px;
    }

    .adaptive-dialog .el-dialog__footer {
        padding: 15px;
    }
}

.btn {
    color: #333;
}

.cancelBtn:hover {
    color: #ffc200;
    border-color: #ffc200;
    background-color: #fffbf0;
}
</style>